package edu.cmu.cs.webapp.ioms.actions.product;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.ClientDAOImpl;
import edu.cmu.cs.webapp.ioms.dao.impl.ProductDAOImpl;
import edu.cmu.cs.webapp.ioms.models.Product;
import edu.cmu.cs.webapp.ioms.models.PurchaseOrder;
import edu.cmu.cs.webapp.ioms.models.impl.ProductImpl;
import edu.cmu.cs.webapp.ioms.ui.wizards.product.ProductWizard;
import edu.cmu.cs.webapp.ioms.views.OrderDetailsView;
import edu.cmu.cs.webapp.ioms.views.ProductView;

public class EditPoductViewAction implements IViewActionDelegate {

	private Product model;
	private ProductView _view;

	@Override
	public void init(IViewPart view) {
		this._view = (ProductView) view;

	}

	@Override
	public void run(IAction action) {
		// if (this.model != null) {
		// ProductWizard
		ProductWizard wizard = new ProductWizard(true, model);

		wizard.setWindowTitle("Edit Product Information");
		WizardDialog dialog = new WizardDialog(_view.getViewSite().getShell(),
				wizard);
		dialog.setBlockOnOpen(true);
		dialog.open();

		// just either ok or cancel
		int returnCode = dialog.getReturnCode();

		if (returnCode == org.eclipse.jface.window.Window.OK) {
			// edit order
			// DAO goes here
			try {
				new ProductDAOImpl().updateProd(wizard.getModel());

				this._view.refreshProductsView();

			} catch (DataAccessException e) {
			}
		}

		// }

	}

	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			// for testing purpose, using the purchaesorder class

			if (obj instanceof Product) {
				// manually create a new product
				this.model = (Product) obj;
			}
		}
	}
}
